package com.balance.anole.erp.component;

import java.util.Calendar;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;

import com.balance.anole.business.to.BusinessDateTO;
import com.balance.anole.client.common.service.CommonService;
import com.balance.anole.erp.util.Messages;
import com.balance.anole.erp.util.ServicesCenter;
import com.balance.anole.utils.DateUtil;

public class TextClock extends Composite {

	final CommonService cs = ServicesCenter.getServicesCenter().getService(CommonService.class);

	/**
	 * Create the composite
	 *
	 * @param parent
	 * @param style
	 */
	public TextClock(Composite parent, int style) {
		super(parent, style);

		final BusinessDateTO businessDate = cs.getBusinessDate();

		if(businessDate == null){
			MessageDialog.openError(parent.getShell(), Messages.DIALOG_INFO_ERROR, "交易日不存在！");
			return;
		}

		this.setLayout(new FormLayout());

		Label label_businessDateData = new Label(this,SWT.LEFT);
		label_businessDateData.setText(DateUtil.format(businessDate.getBusinessDate(), DateUtil.DATE_FORMAT_YYYY_MM_DD));
		FormData formData = new FormData();
		formData.top = new FormAttachment(0,0);
		formData.left = new FormAttachment(0,0);
		formData.width = 70;
		formData.height = 20;
		label_businessDateData.setLayoutData(formData);

		final Label label = new Label(this, SWT.LEFT);
		label.setText("");
		formData = new FormData();
		formData.top = new FormAttachment(0,0);
		formData.left = new FormAttachment(label_businessDateData,5);
		formData.width = 70;
		formData.height = 20;
		label.setLayoutData(formData);
		//
		Display.getDefault().timerExec(500, new Runnable(){

			@Override
			public void run() {
				Calendar now = Calendar.getInstance();
				int h = now.get(Calendar.HOUR_OF_DAY);
				int m = now.get(Calendar.MINUTE);
				int s = now.get(Calendar.SECOND);
				String ss = s < 10 ? "0" + s : String.valueOf(s);
				if(! label.isDisposed()){
					label.setText("" + h + ":" + m + ":" + ss);
					Display.getDefault().timerExec(1000, this);
				}
			}

		});

	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	@Override
	public void dispose() {
		super.dispose();
	}
}
